﻿using System;
using System.IO;
using K9Nano.EFCore;
using K9Nano.Share.Exceptions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Configuration;

namespace K9Nano.MySql
{
    public class K9DesignDbContextFactory<TDbContext> : IDesignTimeDbContextFactory<TDbContext> 
        where TDbContext : DbContext
    {
        public virtual TDbContext CreateDbContext(string[] args)
        {
            var connectionString = GetConnectionString();
            var optionsBuilder = new DbContextOptionsBuilder<TDbContext>();
            optionsBuilder.UseMySql(connectionString, CreateBuilder());

            return (TDbContext)Activator.CreateInstance(typeof(TDbContext), optionsBuilder.Options, new DesignDbContextHelper());
        }

        protected virtual Action<MySqlDbContextOptionsBuilder> CreateBuilder()
        {
            return null;
        }
 
        protected virtual string GetConnectionString()
        {
            var path = Directory.GetCurrentDirectory();
            var configPath = Path.Combine(path, "config");
            var configuration = new ConfigurationBuilder()
                .SetBasePath(configPath)
                .AddJsonFile("appsettings.json", false)
                .AddJsonFile("appsettings.Development.json", true)
                .Build();
            var connectionString = configuration["Database:ConnectionString"];
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new K9Exception("Can not find ConnectionString in appsettings.json");
            }

            return connectionString;
        }
    }
}